
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.Text;

using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.Security;

namespace Articles
{
	public class FileSysArticleAttachBizRules : Syrinx.BaseBizRules
	{
		public IBizObjList getArticleAttachmentGroups(IApplication app, IRuleContext context, Swaf.BGuid.Guid articleId)
		{
			FlexiMap m = new FlexiMap();
			m.put("articleId", articleId);
			IBizObjList groups = app.appData.get("DA.Articles.GetArticleAttachmentGroups", m) as IBizObjList;
			return groups;
		}

		public IBizObjList getArticleAttachmentGroupsWithFiles(IApplication app, IRuleContext context, Swaf.BGuid.Guid articleId)
		{
			FlexiMap m = new FlexiMap();
			IResults rc;
			m.put("articleId", articleId);
			IBizObjList groups = app.appData.get("DA.Articles.GetArticleAttachmentGroupsWithFiles", m) as IBizObjList;
			if (groups != null)
			{
				IBizObj fileQuery = app.bizObjMgr.create("FileSysQueryInfo");
				foreach (IBizObj group in groups)
				{
					bool authorized = true;
					foreach (IBizObj file in (IBizObjList)group.get("files"))
					{
						if (!CurrentPrincipal.hasPrivilege(
							new StringBuilder(100).Append("AppFunctions.FileSysCache-").Append(ActiveCompanyId).Append(file.get("fileCacheName")).ToString()))
							authorized = false;
						else
							file.put("authorized", true);
						fileQuery.put("cacheName", file.get("fileCacheName"));
						fileQuery.put("name", file.get("filePathName"));
						rc = context.RuleGroup.execute(context, "getFileSysFileDetails", fileQuery);
						IBizObj fileInfo = rc.CallResults as IBizObj;
						if(fileInfo != null)
							file.put("size", calculateSizeString((Int64)fileInfo.get("size")));
						string fileName = (string)file.get("filePathName");
						file.put("fileImageUrl", string.Format("/img/{0}/FsSize/FileTypeImages/{1}.image",
									ActiveCompany.get("settings.defaultMediaCatalogName"),
									fileName.Substring(fileName.LastIndexOf('.') + 1)));
						string shortName = "/" + ActiveCompany.get("shortName");
						file.put("fileUrl", string.Format("/filesys{0}/{1}/{2}", shortName, file.get("fileCacheName"), fileName));
					}
					rc = context.RuleGroup.execute(context, "getArticleDetail",
						group.get(authorized ? "authorizedArticleId" : "unauthorizedArticleId"),
						!app.resMgr.UsingBuiltInCulture, DetailLevel.fullDetails, true, true, null);
					IBizObj article = rc.CallResults as IBizObj;
					group.put("displayArticle", article);
				}
			}
			return groups;
		}

		protected string calculateSizeString(Int64 size)
		{
			if (size < 1000)
				return size + " Bytes";
			if (size < 1000000)
				return (size / 1024M).ToString("N01") + " KB";
			return (size / 1024000M).ToString("N01") + " MB";
		}

		public IBizObj updateArticleAttachmentGroup(IApplication app, IRuleContext context, IBizObj group)
		{
			if (group.isNew)
			{
				group.put("id", new Swaf.BGuid.Guid());
				app.appData.put("DA.Articles.AddArticleAttachmentGroup", group);
			}
			else
				app.appData.put("DA.Articles.UpdateArticleAttachmentGroup", group);

			return group;
		}

		public void deleteArticleAttachmentGroup(IApplication app, IRuleContext context, Swaf.BGuid.Guid groupId)
		{
			FlexiMap m = new FlexiMap();
			m.put("groupId", groupId);
			app.appData.put("DA.Articles.DeleteAllArticleAttachments", m);
			app.appData.put("DA.Articles.DeleteArticleAttachmentGroup", m);
		}

		public IBizObjList getAllCompanyArticlesForFileGroup(IApplication app, IRuleContext context)
		{
			FlexiMap m = new FlexiMap();
			m.put("companyId", ActiveCompanyId);
			m.put("treeName", "Articles");
			IBizObjList list = app.appData.get("DA.Articles.GetAllCompanyArticleIdTitle", m) as IBizObjList;

			list.Insert(0, (IBizObj)app.appData.get("ArticleParentDropDown-Root"));

			IBizObj na = app.bizObjMgr.create("Article");
			na.put("id", new Swaf.BGuid.Guid(Guid.Empty));
			na.put("baseTitle", "- Select Article -");
			list.Insert(0, na);
			return list;
		}

		//------------------------------------------------------------------------------------------------

		public IBizObjList getArticleAttachmentGroupFiles(IApplication app, IRuleContext context, Swaf.BGuid.Guid groupId)
		{
			FlexiMap m = new FlexiMap();
			m.put("groupId", groupId);
			IBizObjList files = app.appData.get("DA.Articles.GetArticleAttachments", m) as IBizObjList;
			foreach (IBizObj file in files)
			{
				string fileName = (string)file.get("filePathName");
				file.put("fileImageUrl", string.Format("/img/{0}/FsSize/FileTypeImages/{1}.image",
							ActiveCompany.get("settings.defaultMediaCatalogName"),
							fileName.Substring(fileName.LastIndexOf('.') + 1)));
			}
			return files;
		}

		public void addArticleAttachmentGroupFile(IApplication app, IRuleContext context, IBizObj fileInfo)
		{
			if (((Swaf.BGuid.Guid)fileInfo.get("fileGroupId")).CompareTo(Guid.Empty) == 0)
			{
				IBizObj newGroup = app.bizObjMgr.create("ArticleAttachmentGroup");
				newGroup.put("articleId", fileInfo.get("articleId"));
				newGroup.put("authorizedArticleId", app.appData.get("ArticleParentDropDown-Root.id"));
				newGroup.put("unauthorizedArticleId", app.appData.get("ArticleParentDropDown-Root.id"));
				IResults rc = context.RuleGroup.execute(context, "updateArticleAttachmentGroup", newGroup);
				newGroup = rc.CallResults as IBizObj;
				fileInfo.put("fileGroupId", newGroup.get("id"));
			}
			app.appData.put("DA.Articles.AddArticleAttachment", fileInfo);
		}

		public void updateArticleAttachmentGroupFile(IApplication app, IRuleContext context, IBizObj fileInfo)
		{
			app.appData.put("DA.Articles.UpdateArticleAttachment", fileInfo);
		}

		public void deleteArticleAttachmentGroupFile(IApplication app, IRuleContext context, Swaf.BGuid.Guid fileId)
		{
			FlexiMap m = new FlexiMap();
			m.put("id", fileId);
			app.appData.put("DA.Articles.DeleteArticleAttachment", m);
		}
	}
}
